//
//  SHTableViewController.m
//  youjian03
//
//  Created by 常琼 on 14/10/20.
//  Copyright (c) 2014年 com.shouhuobao. All rights reserved.
//

#import "SHTableViewController.h"
#import "SHTableViewCell.h"
#import "RootViewController.h"

#import "SHMyPostModel.h"
#import "SHPingViewController.h"
#import "HMNavigationController.h"
#import "SHGenViewController.h"
#import "SHgengenViewController.h"
#import "Reachability.h"


@interface SHTableViewController ()<SHCellDelegate,PingDelegate>
@property(nonatomic,strong) NSMutableArray *models ;
@property(nonatomic,assign) int isHaveWifi;//是否有网络


@property (nonatomic, strong) Reachability *conn;

@end

@implementation SHTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        
    }
    return self;
}

-(NSMutableArray *)models
{
    if (_models ==nil)
    {
        _models = [NSMutableArray array];
    }
    return  _models;
    
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    
    
    
    self.navigationController. interactivePopGestureRecognizer .enabled=NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //"我的寄件"标题
    //添加一个有件快递按钮
    UIButton *youjian =  [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 69, 17)];
    [youjian setTitle:@"我的寄件" forState:UIControlStateNormal];
    [youjian setTitleColor:[UIColor redColor] forState: UIControlStateNormal];
    
    [youjian setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    
    youjian.userInteractionEnabled = NO;
    self.navigationItem.titleView = youjian;
    
    
    //添加左侧按钮
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"back" highImageName:@"back" target:self action:@selector(leftButton)];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(erweima:) name:@"EWM" object:nil];
    
    //判断网络链接
    
    self.isHaveWifi =  [self isConnectionAvailable];
    
    if(self.isHaveWifi != 0)
    {
        
        
        //请求我的寄件列表
        NSString *token = @"";
        //--------------------------sql text------------------------------//
        // 1.获得数据库文件的路径
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *filename = [doc stringByAppendingPathComponent:@"youjian.sqlite"];
        
        
        // 2.得到数据库
        FMDatabase *db = [FMDatabase databaseWithPath:filename];
        if([db open])
        {
            
            FMResultSet *resultset =  [db executeQuery:@"select * from userinfo"];
            while ([resultset next]) {
                token = [resultset stringForColumn:@"token"];
                
            }
            
        }
        //--------------------------sql end------------------------------//
        
        
        
        NSDictionary *dic  = @{@"token":token};
        
        
        [MBProgressHUD showMessage:@"请稍后..."];
        [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(overTime) userInfo:nil repeats:NO];
        
        
        
        [SHHTTPTOOL PostWithString:dic andAction:@"userSendList" success:^(id responseObj) {
            
            NSArray *array = ((NSDictionary *)responseObj[@"msg"])[@"list"];
            
            for(int i = 0 ;i<array.count;i++)
            {
                SHMyPostModel *model = [[SHMyPostModel alloc] init];
                NSDictionary *dic =  (NSDictionary *)array[i];
                model.deliverId =  dic[@"deliverId"];
                model.companyname = dic[@"companyName"];
                model.audio = [NSString stringWithFormat:@"%@%@", SHAPIURL_VOICE_B,((NSDictionary *)dic[@"offerAudio"])[@"audio"]];
                model.duration = ((NSDictionary *)dic[@"offerAudio"])[@"duration"];
                model.name = dic[@"courierName"];
                model.headico = [NSString stringWithFormat:@"%@%@", SHAPIURL_PHOTO_B,dic[@"headico"]];
                model.hascomment = dic[@"hasComment"];
                model.finishtime = dic[@"finishTime"];
                model.typeNo = dic[@"companyCode"];
                
                [self.models addObject:model];
            }
            if (array.count == 0)
            {
                MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
                [self.view addSubview:HUD];
                HUD.labelText = @"您还没有寄件订单";
                HUD.mode = MBProgressHUDModeText;
                
                [HUD showAnimated:YES whileExecutingBlock:^{
                    sleep(1.5);
                } completionBlock:^{
                    [HUD removeFromSuperview];
                }];
                
            }
            
            [self.tableView reloadData];
            [MBProgressHUD hideHUD];
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUD];
            MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
            [self.view addSubview:HUD];
            HUD.labelText = @"您还没有寄件订单";
            HUD.mode = MBProgressHUDModeText;
            
            [HUD showAnimated:YES whileExecutingBlock:^{
                sleep(2.5);
            } completionBlock:^{
                [HUD removeFromSuperview];
            }];
            
            
        }];
    
    }

}

-(BOOL) isConnectionAvailable{
    
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    if (!isExistenceNetwork) {
 
        MBProgressHUD  *HUD = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:HUD];
        HUD.labelText =@"当前网络不可用,请检测网络连接";
        HUD.mode = MBProgressHUDModeText;
        
        [HUD showAnimated:YES whileExecutingBlock:^{
            sleep(1.5);
        } completionBlock:^{
            [HUD removeFromSuperview];
        }];

    
    
    }
    
    return isExistenceNetwork;
}

/**
 *  超时
 */
-(void)overTime
{

    [MBProgressHUD hideHUD];

    
    
}

/**
 *  网络
 *
 */
-(BOOL)isExistenceNetwork{
    BOOL isExistenceNetwork = NO;
    Reachability *r = [Reachability reachabilityWithHostName:@"http://www.baidu.com"];
    switch ([r currentReachabilityStatus]) {
        case NotReachable://没有网络。
            isExistenceNetwork=FALSE;
            break;
        case ReachableViaWWAN://没有3G信号。
            isExistenceNetwork=TRUE;
            break;
        case ReachableViaWiFi://没有wifi。
        isExistenceNetwork=TRUE;
        break;
    }
    return isExistenceNetwork;
}


-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    
    
    

}
-(void)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
    
}

/**
 *  弹出二维码
 */
-(void)erweima:(NSNotification *)note
{
    RootViewController *reader = [[RootViewController alloc]init];
    
    [self presentViewController:reader animated:YES completion:^{
        HMLog(@"yijing tanchu");
    }];
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.models.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 191;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SHTableViewCell  *cell= (SHTableViewCell *)[[[NSBundle  mainBundle]  loadNibNamed:@"SHTableViewCell" owner:self options:nil]  lastObject];
    cell.delegate = self;
    SHMyPostModel *m = self.models[indexPath.section];
   
    cell.row = indexPath.section;
    [cell setMyPostModel:m];
    
    
    
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 7.5f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 7.5f;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 30)]   ;
    [headerView setBackgroundColor:HMColor(237, 237, 237)];
    return headerView;
}
- (UIView *) tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *headerView =[[UIView alloc] init];
    [headerView setBackgroundColor:HMColor(237, 237, 237)];
    return headerView;
}
-(void)dealloc
{
    [self.conn stopNotifier];
    [[NSNotificationCenter defaultCenter] removeObserver:self];


}
#pragma mark -SHCellDelegate

///评价传参:订单id
-(void)pingWithOrderId:(NSString *)orderId andRow:(int)row
{
   
    SHPingViewController *pingVc  = [[SHPingViewController alloc] init];
    pingVc.orderId =orderId;
    pingVc .row =row;
    pingVc.delegate = self;
    
    HMNavigationController *nv = [[HMNavigationController alloc] initWithRootViewController:pingVc];
    [self presentViewController:nv animated:YES completion:^{
    }];
    
    
}

//跟踪传惨:运单号
-(void)genWithCodeNo:(NSString *)codeNo  andTypeNo:(NSString *)typeNo
{
    SHgengenViewController *genVc = [[SHgengenViewController alloc] init];
    
    genVc.typeNo = typeNo;
    [self.navigationController pushViewController:genVc animated:YES];
    
    
}

#pragma mark -PingDelegate
-(void)successPingWithRow:(int)row
{
 
    SHMyPostModel *model = self.models[row];
    
    model.hascomment = @"1";//至成"已评价"
    
    
    [self.models replaceObjectAtIndex:row withObject:model];
    [self.tableView reloadData];
}
@end
